﻿using DavidCms.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace DavidCms.Web.Controllers
{
    public class BaseController : Controller
    {
        public BaseController()
        {
        }

        public List<NavigationVO> NavVoList
        {
            get
            {
                Cache cacheHelper = HttpRuntime.Cache;
                string cacheKey = "Common.Navigation";
                //cacheHelper.Insert("1", 1);
                List<NavigationVO> result = (List<NavigationVO>)cacheHelper.Get(cacheKey);
                string Url = Request.Url.Authority;
                if (result == null || result.Count==0)//true)//
                {
                    CmsContext db = new CmsContext();
                    List<NavigationPO> navPoList = db.Navigation.ToList();
                    List<NavigationVO> navVoList = new List<NavigationVO>();
                    foreach (NavigationPO v in navPoList.Where(o => o.ParentId == -1).OrderBy(o => o.Order))
                    {
                        NavigationVO navVO = new NavigationVO()
                        {
                            Id = v.Id,
                            Name = v.Name,
                            EnglishName = v.EnglishName,
                            Type = v.Type,
                            Children = new List<NavigationVO>(),
                        };
                        navVoList.Add(navVO);
                        NavPoToVo(v.Id, Url, navPoList, navVO.Children);
                    }
                    result = navVoList;
                    cacheHelper.Insert(cacheKey, navVoList);
                    //cacheHelper.Insert(cacheKey, navVoList, new SqlCacheDependency("CacheDB", "tb_Business_Navigation"), DateTime.MaxValue, new TimeSpan(12, 0, 0));
                }
                return result;
            }
        }

        private void NavPoToVo(int parentId, string url, List<NavigationPO> navPoList, List<NavigationVO> navVoList)
        {
            foreach (NavigationPO v in navPoList.Where(o => o.ParentId == parentId).OrderBy(o => o.Order))
            {
                NavigationVO navVO = new NavigationVO()
                {
                    Id = v.Id,
                    Name = v.Name,
                    EnglishName = v.EnglishName,
                    Type = v.Type,
                    Children = new List<NavigationVO>(),
                };
                navVoList.Add(navVO);
                NavPoToVo(v.Id, url, navPoList, navVO.Children);
            }
        }
    }
}